import React, { useEffect, useState, useCallback } from 'react';
import {
  View,
  StyleSheet,
  FlatList,
  Text,
  TextInput,
  TouchableOpacity,
  Alert,
} from 'react-native';
import { useNavigation } from '@react-navigation/native';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import { useTheme } from '../theme/ThemeContext';
import { Card } from '../components/Card';
import { Button } from '../components/Button';
import { Plan } from '../database/models';
import { createPlan, getPlans, deletePlan } from '../database/database';
import { formatDate } from '../utils/timeUtils';

export const HomeScreen = () => {
  const navigation = useNavigation();
  const { theme } = useTheme();
  const [plans, setPlans] = useState<Plan[]>([]);
  const [isAddingPlan, setIsAddingPlan] = useState(false);
  const [newPlanName, setNewPlanName] = useState('');

  const loadPlans = useCallback(async () => {
    try {
      const loadedPlans = await getPlans();
      setPlans(loadedPlans);
    } catch (error) {
      console.error('Error loading plans:', error);
      Alert.alert('错误', '加载计划失败');
    }
  }, []);

  useEffect(() => {
    loadPlans();
  }, [loadPlans]);

  const handleAddPlan = async () => {
    if (!newPlanName.trim()) {
      Alert.alert('提示', '请输入计划名称');
      return;
    }

    try {
      await createPlan({ name: newPlanName.trim() });
      setNewPlanName('');
      setIsAddingPlan(false);
      loadPlans();
    } catch (error) {
      console.error('Error creating plan:', error);
      Alert.alert('错误', '创建计划失败');
    }
  };

  const handleDeletePlan = async (plan: Plan) => {
    Alert.alert(
      '确认删除',
      `确定要删除计划"${plan.name}"吗？`,
      [
        {
          text: '取消',
          style: 'cancel',
        },
        {
          text: '删除',
          style: 'destructive',
          onPress: async () => {
            try {
              await deletePlan(plan.id);
              loadPlans();
            } catch (error) {
              console.error('Error deleting plan:', error);
              Alert.alert('错误', '删除计划失败');
            }
          },
        },
      ]
    );
  };

  const renderItem = ({ item }: { item: Plan }) => (
    <Card
      onPress={() => navigation.navigate('Timer', { planId: item.id, planName: item.name })}
    >
      <View style={styles.cardHeader}>
        <Text style={[styles.planName, { color: theme.colors.text }]}>
          {item.name}
        </Text>
        <TouchableOpacity
          onPress={() => handleDeletePlan(item)}
          style={styles.deleteButton}
        >
          <Icon name="delete" size={24} color={theme.colors.error} />
        </TouchableOpacity>
      </View>
      <Text style={[styles.date, { color: theme.colors.grey }]}>
        创建于 {formatDate(item.createdAt)}
      </Text>
    </Card>
  );

  return (
    <View style={[styles.container, { backgroundColor: theme.colors.background }]}>
      <FlatList
        data={plans}
        renderItem={renderItem}
        keyExtractor={(item) => item.id.toString()}
        contentContainerStyle={styles.list}
      />
      
      {isAddingPlan ? (
        <View style={styles.addPlanContainer}>
          <TextInput
            style={[
              styles.input,
              {
                color: theme.colors.text,
                borderColor: theme.colors.border,
                backgroundColor: theme.colors.card,
              },
            ]}
            placeholder="输入计划名称"
            placeholderTextColor={theme.colors.grey}
            value={newPlanName}
            onChangeText={setNewPlanName}
            autoFocus
          />
          <View style={styles.addPlanButtons}>
            <Button
              title="取消"
              variant="outline"
              onPress={() => {
                setIsAddingPlan(false);
                setNewPlanName('');
              }}
              style={styles.addPlanButton}
            />
            <Button
              title="确定"
              onPress={handleAddPlan}
              style={styles.addPlanButton}
            />
          </View>
        </View>
      ) : (
        <Button
          title="添加计划"
          onPress={() => setIsAddingPlan(true)}
          style={styles.addButton}
        />
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  list: {
    padding: 16,
  },
  cardHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  planName: {
    fontSize: 18,
    fontWeight: '600',
    flex: 1,
  },
  date: {
    fontSize: 14,
    marginTop: 8,
  },
  deleteButton: {
    padding: 4,
  },
  addButton: {
    margin: 16,
  },
  addPlanContainer: {
    padding: 16,
    borderTopWidth: 1,
  },
  input: {
    borderWidth: 1,
    borderRadius: 8,
    padding: 12,
    marginBottom: 16,
  },
  addPlanButtons: {
    flexDirection: 'row',
    justifyContent: 'flex-end',
  },
  addPlanButton: {
    marginLeft: 8,
  },
}); 